package com.my.aop;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(20)
@Aspect
@Component
public class LogAspect {

	/**
	 * 对所有计算方法切入<br/>
	 * 第一个 * 表示任意返回值 <br/>
	 * 第二和第三个 * 表示包路径不限 <br/>
	 * 第四个 * 表示类中的方法不限 <br/>
	 */
	@Pointcut("execution(* com.*.*.Calc.*(..))")
	public void cut() {}

	@Before("cut()")
	public void before(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		Object[] args = joinPoint.getArgs();
		System.out.println(String.format("====>LogAspect, before method = %s, args= %s ", methodName, Arrays.asList(args)));
	}

	@After("cut()")
	public void after(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println(String.format("<====LogAspect, after method = %s ", methodName));
	}

	@AfterReturning(value = "cut()", returning = "result")
	public void afterReturning(JoinPoint joinPoint, Object result) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println(String.format("<====LogAspect, afterReturning method = %s, result = %s ", methodName, result));
	}

	@AfterThrowing(value = "cut()", throwing = "e")
	public void afterThrowing(JoinPoint joinPoint, Exception e) {
		String methodName = joinPoint.getSignature().getName();
		System.out.println(String.format("<====LogAspect, afterThrowing method = %s, throw exceptions = %s", methodName, e));
	}

}
